import http from '@/common/request'
import browser from '@/common/browser'
import store from '../store'
import pinyin from '@/common/pinyin.js';
import MsgManager from '@/uni_modules/uni-im/common/msgManager.js';
import uniImStorage from '@/uni_modules/uni-im/common/uni-im-storage.js'
import appcheckauth from "@/common/appcheckauth.js"
export default {
    //合并消息
    merage_data(data1,data2){
        var newdata={};
        if(data1.length>0){
            for(var i in data1){
                var item = data1[i];
                var indexkey='';
                if(indexkey=='' && item.id)indexkey=item.id;
                if(indexkey=='' && item.msgId && item.msgId=='local')indexkey=item.msgId;
                if(indexkey=='' && item.time)indexkey=item.time;
                if(indexkey=='' && item.create_time)indexkey=item.create_time;
                newdata[indexkey]=item;
            }  
        }
        if(data2.length>0){
            for(var i in data2){
                var item = data2[i];
                var indexkey='';
                if(indexkey=='' && item.id)indexkey=item.id;
                if(indexkey=='' && item.msgId && item.msgId=='local')indexkey=item.msgId;
                if(indexkey=='' && item.time)indexkey=item.time;
                if(indexkey=='' && item.create_time)indexkey=item.create_time;
                newdata[indexkey]=item;
            }  
        }
        var data=[];
        if(newdata){for(var i in newdata){data.push(newdata[i]);}}
        data = data.sort((a, b) => {return Math.round(a.create_time/1000) - Math.round(b.create_time/1000)})
        return data;
    },
	//文本转json
	returnParse(txt) {
		return typeof txt=='object'?txt:JSON.parse(txt);
	},
    inArray: function (search, array) {
        if(typeof array=='string')array =array.split(',');
        for (var i in array) {
          if (array[i] == search) {return true;}
        }
        return false;
    },
	//字典翻译
	findLabel(arr, text) {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].value == text) {
				return arr[i].label
				break;
			}
		}
	},
	//判断按钮权限
	permissions(permissions) {
		var data = store.state.permissions
		var have = data.indexOf(permissions)
		if (have !== -1) {
			return true
		}
	},
	//判断单个角色权限
	hasRole(Role) {
		var data = store.state.userRole
		var have = data.indexOf(Role)
		if (have !== -1) {
			return true
		}
	},
	//判断多个角色权限
	hasRoles(Roles) {
		var data = store.state.userRole

		function fidrole(Roles) {
			for (var i = 0; i < Roles.length; i++) {
				var have = data.indexOf(Roles[i])
				if (have !== -1) {
					return true
				}
			}
			return false
		}
		return fidrole(Roles)
	},
	//预览单张图片
	previewImagesolo(File) {
		uni.previewImage({
			urls: [File],
		});
	},
	//预览一组图片(图片组,图片索引)
	previewImages(FilePaths, current) {
		uni.previewImage({
			urls: FilePaths,
			current: current
		});
	},
	//观看视频
	openVideo(url){
		uni.navigateTo({
			url: this.get_package_name()+'video/index?url=' + url
		})
	},
    loginwithtoken(token){
        var formData = {'token':token};
        http.request({//手机+验证码
			url: '/auth/loginByToken',
			method: 'POST',
			data:JSON.stringify(formData),
			success: (res) => {
				if (res.data.code == 200) {
                    if(res.data.data.token){
		                uni.setStorageSync('Authorization', res.data.data.token);
				        store.dispatch('get_UserInfo').then(res=>{
                            uni.reLaunch({
            				    url: this.get_package_name()+'index/index'
                                //,success:(res) =>{console.log('success',res);},
                                //fail:(res) =>{console.log('fail',res);},
                                //complete:(res) =>{console.log('complete',res);}
            				})
				        });
                    }
				}
			}
		});
    },//拉取系统配置
    getConfig(){
        var app = getApp();
        http.request({
			url: '/common/getConfig',
			success: (res) => {
				if(res.data.data){
				  app.globalData.appconfig = res.data.data;
				  if(app.globalData.appconfig.navigatorType){
					  store.dispatch('update_navigatorType',app.globalData.appconfig.navigatorType);
				  }
				}
			}
		});
    },//获取推送id
    getuniPushClientId(cb){
        var app = getApp();
        if(app.globalData.pushcid)return app.globalData.pushcid;
        if(app.globalData.pushversion==2){
            uni.getPushClientId({
            	success: (res) => {
       	            let cid = res.cid;
            	    app.globalData.pushcid = cid;
            	    cb && cb(cid);
            	},
            	fail(err) {
            		console.log(err)
            	}
            })
        }else{
            // #ifdef APP-PLUS
            // 页面加载时触发
            plus.push.getClientInfoAsync((info) => {
                 let cid = info["clientid"]; 
            	 app.globalData.pushcid = cid;
            	 cb && cb(cid); 
            });
            setTimeout(()=>{
                this.getuniPushClientId(cb);
            },1000)
	        // #endif
        }
    },
	//操作其他栈页面的值
	changeData: function(step, data, cb) {
	    var pages = getCurrentPages();
	    if (pages.length > 1) {
	        //上一个页面实例对象
	        if (step > 0) {
	            var prePage = pages[pages.length - (1 + step)];
	            prePage.$vm.changeData(data);
	            typeof cb == "function" && cb(true);
	        }
	    }
	},
    //处理推送的消息
    dopushmsg(msg){
		var self = this;
        var app = getApp();
        var data = msg.data.payload;console.log('收到消息',msg);
		if(data.msgContent){
			if(data.msgContent.msgType == 'groupApply'){
				var content = JSON.parse(data.msgContent.content);
				this.setGroupApply(data.groupInfo.userId,content.isadd,content.count);
				return;
			}
		}
        var userInfo = store.state.userInfo;
        var userId = data.fromInfo ? data.fromInfo.userId : 0;
        if(userId!=userInfo.userId){
        if(msg.data.content)msg.data.content=this.filteremoji(msg.data.content);
		this.getPush(data);
        // #ifdef APP-PLUS
        if(msg.data && !msg.data.title || !msg.data.content)msg.type='click';
        if(msg.type=='receive' && userInfo &&  userInfo.userId){
            var is_PushMessage=1;
            if(data.msgContent && data.msgContent.disturb=='Y')is_PushMessage=0;//静默消息
            //console.log('conversation_id-',app.globalData.conversation_id,is_PushMessage);
            var check_conver_id='';
            if(app.globalData.conversation_id && data.msgContent && data.msgContent.cache_id){
                if(data.groupInfo && data.groupInfo.userId){
                    check_conver_id = this.getConversationId(data.groupInfo.userId,'GROUP',data.fromInfo.userId);
                }else{
                    check_conver_id = app.globalData.conversation_id;
                }
                if(check_conver_id && data.msgContent.cache_id.indexOf(check_conver_id)>0)is_PushMessage=0;//静默消息
            }//console.log('conversation_id',check_conver_id,data.msgContent.cache_id,is_PushMessage);
            if(is_PushMessage==1){
            if(data.fromInfo && data.fromInfo.portrait && typeof data.fromInfo.portrait =='string'){
        		uni.getImageInfo({
        			src: data.fromInfo.portrait,
        			success: function (image) {
        			    msg.data.icon=image.path;
                        uni.createPushMessage(msg.data);
        			}
        		});
            }else{
                uni.createPushMessage(msg.data);
            }}
        }
	    // #endif
        //监听系统通知栏消息点击事件
        if(msg.type=='click'){//console.log(msg);
            if(data.pushType=='MSG'){//消息
                 var windowType ='SINGLE';
                 if(data.groupInfo && data.groupInfo.userId){
                    windowType ='GROUP';
                    userId =data.groupInfo.userId; 
                 }
                 setTimeout(()=>{
                    uni.navigateTo({
    					url: this.get_package_name()+'chatWindow/index?userId=' + userId + '&windowType=' + windowType
    				});
                 },500);
             }
             if(data.pushType=='NOTICE'){//提醒
                if(data.msgContent.topicReply){//朋友圈
					if(store.state.navigatorType == 1){
						uni.reLaunch({
						    url: this.get_package_name()+'index/index?index=2'
						})
					}else{
						uni.navigateTo({
							url: this.get_package_name()+'pyq/index'
						});
					}
                }
             }
        }
        }
    },
	//根据后缀判断文件类型
	getFileType(fileName) {
		// 后缀获取
		let suffix = '';
		// 获取类型结果
		let result = '';
		try {
			const flieArr = fileName.split('.');
			suffix = flieArr[flieArr.length - 1];
		} catch (err) {
			suffix = '';
		}
		// fileName无后缀返回 false
		if (!suffix) {
			return false;
		}
		suffix = suffix.toLocaleLowerCase();
		// 图片格式
		const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
		// 进行图片匹配
		result = imglist.find(item => item === suffix);
		if (result) {
			return 'image';
		}
		// 匹配txt
		const txtlist = ['txt'];
		result = txtlist.find(item => item === suffix);
		if (result) {
			return 'txt';
		}
		// 匹配 excel
		const excelist = ['xls', 'xlsx'];
		result = excelist.find(item => item === suffix);
		if (result) {
			return 'excel';
		}
		// 匹配 word
		const wordlist = ['doc', 'docx'];
		result = wordlist.find(item => item === suffix);
		if (result) {
			return 'word';
		}
		// 匹配 pdf
		const pdflist = ['pdf'];
		result = pdflist.find(item => item === suffix);
		if (result) {
			return 'pdf';
		}
		// 匹配 ppt
		const pptlist = ['ppt', 'pptx'];
		result = pptlist.find(item => item === suffix);
		if (result) {
			return 'ppt';
		}
		// 匹配 视频
		const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
		result = videolist.find(item => item === suffix);
		if (result) {
			return 'video';
		}
		// 匹配 音频
		const radiolist = ['mp3', 'wav', 'wmv'];
		result = radiolist.find(item => item === suffix);
		if (result) {
			return 'radio';
		}
		// 其他 文件类型
		return 'other';
	},
	//新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx
	onOpenDoc(e) {
		uni.downloadFile({
			url: e,
			success: function(res) {
				var filePath = res.tempFilePath;
				uni.openDocument({
					filePath: filePath,
					success: function(res) {
						console.log('打开文档成功');
					}
				});
			}
		});
	},
	//模拟浏览器打开第三方链接
	openWebView(url) {
		uni.navigateTo({
			url: this.get_package_name()+'webview/webview?weburl=' + encodeURIComponent(url)
		})
	},
	//获取时间format
	getNewDate(format, add0,datetime) {
		//获取当前时间
		function addZero(val) {
			//补零
			if (add0) {
				return val <= 9 ? '0' + val : val;
			} else {
				return val
			}
		}
		var date = new Date()
		if(datetime){
			date=new Date(datetime)
		}
		var year = date.getFullYear(),
			month = addZero(date.getMonth() + 1),
			strDate = addZero(date.getDate()),
			hours = addZero(date.getHours()),
			minutes = addZero(date.getMinutes()),
			seconds = addZero(date.getSeconds());
		switch (format) {
			case 'y':
				return year;
				break;
			case 'm':
				return month;
				break;
			case 'd':
				return strDate;
				break;
			case 'h':
				return hours;
				break;
			case 'mm':
				return minutes;
				break;
			case 'ss':
				return seconds;
				break;
			case 'ymd':
				return year + '/' + month + '/' + strDate;
				break;
			case 'hmmss':
				return hours + ':' + minutes + ':' + seconds;
				break;
			default:
				return year + '/' + month + '/' + strDate + ' ' + hours + ':' + minutes + ':' + seconds;
				break;
		}
	},
	//获取本地存储object/初始化
	getKeyObjectStorage(keyname) {
		try {
			var chatData = uni.getStorageSync(keyname);
			if (chatData) {
				chatData = this.returnParse(chatData)
				return chatData
			} else {
				chatData = new Object()
				return chatData
			}
		} catch (e) {
			return new Object()
		}
	},
	clearMsgTime(type,fid,conversation_id){
	    if(fid>0){
    		http.request({
    			url: '/my/setclearmsgtime?type=' + type + '&fid=' + fid,
    			success: (res) => {
    				JSON.stringify(res)
    			}
    		});
        }
        if(conversation_id){
    		let key_before = "uni-im-msg:"+conversation_id
    		if(!conversation_id){return true;}
            let {
    			keys,currentSize,limitSize
    		} = uni.getStorageInfoSync()
    		keys = keys.filter(k => k.indexOf(key_before) === 0)
    		if (keys.length == 0) {return true;}
            for(var i in keys){
                uni.removeStorageSync(keys[i]);
            }
            return true;
        }
	},
	loadMore({
		url='xxx/list/',
		queryParams={
			refreshing:false,
			pageNum:1,
			status: 'more',//more loading前 loading loading中 noMore 没有更多了
			pageSize:10
		},
		status='0'//0无更多数据 1持续加载 2重新加载 3无数据+清空数据
	}){
		return new Promise((resolve, reject) => {
			http.request({
				url:url+'&page='+(queryParams.refreshing ? 1 : queryParams.pageNum) +'&pageSize=' +queryParams.pageSize,
				success: res => {
					if (res.data.code == 200) {
						let list = [];
						let data = res.data.data.data;
						if (queryParams.refreshing&&data == ''||queryParams.refreshing&&data.length==0) {
							queryParams.status='noMore'
							resolve({
								queryParams:queryParams,
								list:list,
								status:'3'
							})
							return
						}
						if (data == ''||data.length==0) {
							queryParams.status='noMore'
							resolve({
								queryParams:queryParams,
								list:list,
								status:'0'
							})
							return
						}
						for (let i = 0, length = data.length; i < length; i++) {
							var item = data[i];
							list.push(item);
						}
						if (queryParams.refreshing) {
							queryParams.refreshing = false;
							queryParams.pageNum = 2;
							queryParams.status='more'
							resolve({
								queryParams:queryParams,
								list:list,
								status:'2'
							})
						} else {
							queryParams.pageNum += 1;
							queryParams.status='more'
							resolve({
								queryParams:queryParams,
								list:list,
								status:'1'
							})
						}
					} else {
						reject(res);
					}
				},
				fail: (res) => {
					reject(res);
				}
			});
		});
	},//撤回消息
    revokeMsg(content){
         var windowType = content.windowType=='GROUP'?'GROUP':'SINGLE';
         var conversation_id = this.getConversationId(content.userId,windowType);                     
		store.dispatch('getchatDatalist',conversation_id);
		var msgList = store.state.chatDatalist[conversation_id].list;//console.log(conversation_id,msgList);
        let dataindex = msgList.findIndex(msg =>  (msg.msgId && content.msgId && content.msgId!='local' && msg.msgId!='local' && msg.msgId == content.msgId) || (msg.cache_id && msg.cache_id==content.cache_id) );
        //console.log(dataindex);
        if(dataindex>-1){
             msgList[dataindex].type=3;
             if(content.msgId && content.msgId!='local')msgList[dataindex].msgId=content.msgId;
             msgList[dataindex].content=content.content;
             msgList[dataindex].msgType="ALERT";
             //console.log(dataindex,msgList[dataindex]);
            store.dispatch('updateChatById', {
        		conversation_id: conversation_id,
        		data: msgList
        	});
            this.updateCacheMsg(msgList[dataindex]);
        }else{
            content.type=3;
            content.msgType="ALERT";
            this.updateCacheMsg(content);
        }
        var key  = content.windowType=="GROUP"?"GROUP"+content.userId:content.userId;
        var msgLists = store.state.chatlist[key];
        msgLists.num=0;
        msgLists.content = content.content;//console.log(msgLists);
		store.dispatch('updateChatListInfoById', {
			userId: key,
			data: msgLists
		});
        // #ifdef APP-PLUS
        var tongzhilist = plus.push.getAllMessage();
        for(var i in tongzhilist){
            var item  = tongzhilist[i];
            if(item.payload && item.payload.msgContent && item.payload.msgContent.cache_id && item.payload.msgContent.cache_id==content.cache_id){
                plus.push.remove(item);
            }
        }
        //console.log('Message',tongzhilist);
		// #endif
    },
    updateCacheMsg(data){
        var is_true = false;//console.log(data);
        if(data && data.id){//console.log('updateCacheMsg1');
            let keyArray = data.id.split('-')
    		let index = keyArray.length == 5 ? keyArray.pop():false
    		let key = keyArray.join('-')
    		let res = uni.getStorageSync(key);
            if(res){//console.log(index,key);
                res[index] = Object.assign(res[index], data);
    		    uni.setStorageSync(key, res);
                is_true = true;
            }
        }
        if(!is_true && data.cache_id){
            let keyArray = data.cache_id.split('-')
    		let index = keyArray.length == 5 ? keyArray.pop():false
    		let key = keyArray.join('-')
    		let res = uni.getStorageSync(key);
            if(res){//console.log(index,key);
                res[index] = Object.assign(res[index], data);
    		    uni.setStorageSync(key, res);
                is_true = true;
            }else{
                var key_before;
                if(data.conversation_id){
                    key_before = "uni-im-msg:"+data.conversation_id;
                }else{
            		let index = keyArray.length == 4 ? keyArray.pop():false
            		key_before = keyArray.join('-')
                }
                //console.log('updateCacheMsg3',key_before);
                let {
        			keys,
        			currentSize,
        			limitSize
        		} = uni.getStorageInfoSync();
        		keys = keys.filter(k => k.indexOf(key_before) === 0)
        		if (keys.length == 0) {
        			return false;
        		}
                for(var i in keys){
                    let res = uni.getStorageSync(keys[i])||[];
                    if(res){
                        var is_update = false;
                        for(var y in res){
                            if(res[y].cache_id==data.cache_id){
                                res[y] =Object.assign(res[y], data);is_update=true;
                            }
                        }
                        if(is_update){
                            uni.setStorageSync(keys[i], res);return true;
                        }
                    }
                }
            }
        }return false;
    },
	//接收推送消息
	getPush(resbody) {//console.log(resbody);
		var pushType = resbody.pushType //推送类型
		if (pushType == 'MSG') {
			if(resbody.msgContent.msgType=='TRTC_VOICE_START'||resbody.msgContent.msgType=='TRTC_VIDEO_START'){
				//音视频开始拦截
				return
			}
			var userId=resbody.fromInfo.userId
			var windowType='SINGLE'
			if(resbody.groupInfo.userId){
				userId=resbody.groupInfo.userId
				windowType='GROUP'
			}
			this.pushInMsg({
				type: resbody.msgContent.msgType == 'ALERT' ? 3 : 1, //显示类型 1左侧 2右侧 3中间
				msgContent: resbody.msgContent.content, //msg内容
				msgType: resbody.msgContent.msgType, //msgType信息类型
				windowType: windowType, //聊天室类型 SINGLE GROUP
				time: resbody.createTime, //时间
				fromInfo:resbody.fromInfo,//来源信息
				groupInfo:resbody.groupInfo,//群信息
				userId: userId,//talktoId
				personId:resbody.fromInfo.userId,
				msgId:resbody.msgId,//消息Id
				cache_id:resbody.msgContent.cache_id,//消息缓存Id
				disturb:resbody.msgContent.disturb,//是否静默消息
				top:resbody.msgContent.top//是否置顶
			})
			return
		}
		if (pushType == 'NOTICE') {//红点通知等
			if(resbody.msgContent.topicReply && resbody.msgContent.topicReply.count){
				store.commit('update_topicReply',resbody.msgContent.topicReply)
			}
			if(resbody.msgContent.topicRed && resbody.msgContent.topicRed.portrait){
				store.commit('update_topicRed',resbody.msgContent.topicRed)
			}
			if(resbody.msgContent.friendApply && resbody.msgContent.friendApply.count){
				store.commit('update_friendApply',resbody.msgContent.friendApply)
			}
			if(resbody.msgContent.msgType){
			     var content = JSON.parse(resbody.msgContent.content);
			     switch(resbody.msgContent.msgType){
			         case 'editNickname'://修改群昵称
                     if(content.uid && content.nickname && resbody.groupInfo){
                        var groupInfo = resbody.groupInfo;
                        var conversation_id =  this.getConversationId(groupInfo.userId,'GROUP');
            			store.dispatch('getchatDatalist',conversation_id);
            			var chatWindowData = store.state.chatDatalist[conversation_id].list;
                        for(var i in chatWindowData){
                            if(chatWindowData[i].personId==content.uid)chatWindowData[i].nickName=content.nickname;
                        }
                        var namekey = groupInfo.userId+'_'+content.uid;
                        store.dispatch('addGroupNameData', {
                    		id: namekey,
                    		data: content.nickname
                    	});
                        store.dispatch('updateChatById', {
                    		conversation_id: conversation_id,
                    		data: chatWindowData
                    	});
                     }
                     break;
			         case 'revokeMsg'://撤回消息
                     this.revokeMsg(content);
                     break;
                     
			     }
			}
		}
		if (pushType == 'BIG') {//大消息
			var bigId=resbody.msgContent.content
			http.request({
				url: '/chat/getBigMsg/'+bigId,
				success: (res) => {
					if (res.data.code == 200) {
						var resbody=res.data.data
						var userId=resbody.fromInfo.userId
						var windowType='SINGLE'
						if(resbody.groupInfo.userId){
							userId=resbody.groupInfo.userId
							windowType='GROUP'
						}
						this.pushInMsg({
							type: resbody.msgContent.msgType == 'ALERT' ? 3 : 1, //显示类型 1左侧 2右侧 3中间
							msgContent: resbody.msgContent.content, //msg内容
							msgType: resbody.msgContent.msgType, //msgType信息类型
							windowType: windowType, //聊天室类型 SINGLE GROUP
							time: resbody.createTime, //时间
							fromInfo:resbody.fromInfo,//来源信息
							groupInfo:resbody.groupInfo,//群信息
							userId: userId,//talktoId
							personId:resbody.fromInfo.userId,
							msgId:resbody.msgId,//消息Id
				            cache_id:msgContent.cache_id,//消息缓存Id
							disturb:resbody.msgContent.disturb,//是否静默消息
							top:resbody.msgContent.top//是否置顶
						})
					}
				}
			});
			return
		}
	},
	// 接收到的聊天推送
	pushInMsg({
	   cache_id,
		msgId,//消息Id
		msgContent,//内容
		msgType,//消息类型
		windowType,//聊天室类型 SINGLE GROUP
		userId,//聊天对象ID
		personId,//发送人ID
		time,//时间
		type,//显示类型 1左侧 2右侧 3中间
		fromInfo,//来源
		groupInfo,//群信息
		disturb,//是否静默消息
		top//是否置顶
	}) {//console.log('接收到的聊天推送',msgContent);
		var msgTypeLabel = ''; //消息类型
		if (msgType == 'TEXT' ||　msgType == 'TEXTAT' || msgType == 'ALERT') {
			msgTypeLabel = msgContent;
		}
		if (msgType == 'IMAGE') {
			msgTypeLabel = '[图片]';
		}
		if (msgType == 'VOICE') {
			msgTypeLabel = '[语音]';
		}
		if (msgType == 'VIDEO') {
			msgTypeLabel = '[视频]';
		}
		if (msgType == 'LOCATION') {
			msgTypeLabel = '[位置]';
		}
		if (msgType == 'COLLECTION') {
			msgTypeLabel = '[收藏]';
		}
		if (msgType == 'CARD') {
			msgTypeLabel = '[名片]';
		}
		if (msgType == 'FILE') {
			msgTypeLabel = '[文件]';
		}
		if (msgType == 'TRTC_VOICE_END') {
			msgTypeLabel = '[语音通话]'
		}
		if (msgType == 'TRTC_VIDEO_END') {
			msgTypeLabel = '[视频通话]'
		}
		if (msgType == 'manyMsg') {
			msgTypeLabel = '[聊天记录]';
		}
		store.dispatch('createChatObj',{
			userId:userId,
			windowType:windowType,
		}).then(res=>{
            var key  = windowType=="GROUP"?"GROUP"+userId:userId;
            var conversation_id =  this.getConversationId(userId,windowType);
			var localData=res.data
			store.dispatch('getchatDatalist',conversation_id);
			store.dispatch('getChatList');
			var chatWindowData = store.state.chatDatalist[conversation_id].list
			var chatListInfo = store.state.chatlist[key]
			// 找到数组中对象属性值一样的对象并返回
			function arrfindobject({arr,object,key,key2}){
				var result=arr.find(item =>{
				    if(key2){
				        return item[key] == object[key] && item[key2] == object[key2]
				    }else{
				        return item[key] == object[key]
				    }
				});
				return result
			}
			var same=arrfindobject({arr:chatWindowData,object:{
				msgId:msgId,time:time
			},key:'msgId',key2:'time'})
			if(same){
				return
			}
			//离线消息体
			var msgOffline = {
				userId: userId,
                cache_id: cache_id,
				personId: personId,
				nickName: fromInfo.nickName,
				portrait: fromInfo.portrait,
				msgType: msgType,
				content: msgContent,
				time: time,
                create_time : new Date(time).getTime(),
				type: type,
				msgId:msgId,
				windowType: windowType
			}
			
			// 聊天记录体
			var msgList = {}
			if(windowType=='SINGLE'){
				msgList = {
					userId: userId,
					personId: personId,
					nickName: fromInfo.nickName,
					portrait: fromInfo.portrait,
					content: msgTypeLabel,
					time: time,
					num: disturb=='Y' ? 'dot' : (chatListInfo.num ? chatListInfo.num + 1 : 1),
					windowType: windowType,
					disturb:disturb,//是否静默消息
					top:top,//是否置顶
					userType:fromInfo.userType
				}
			}
			if(windowType=='GROUP'){
				msgList = {
					userId: userId,
					personId: personId,
				    personName:fromInfo.nickName,
					nickName: groupInfo.nickName,
					portrait: groupInfo.portrait,
					content: msgTypeLabel,
					time: time,
					num: disturb=='Y' ? 'dot' : (chatListInfo.num ? chatListInfo.num + 1 : 1),
					windowType: windowType,
					disturb:disturb,//是否静默消息
					top:top,//是否置顶
					userType:'GROUP'
				}
			}
            var app = getApp(); //console.log(app.globalData.conversation_id,conversation_id);                    
            if(app.globalData.conversation_id && conversation_id==app.globalData.conversation_id)msgList.num=0;
            if(msgType == 'TEXTAT'){
                var arr = this.returnParse(msgTypeLabel);
                if(msgTypeLabel.indexOf('@')>0 && arr.ids){
                    this.checknotestrcontent = arr.content;
                    var userInfo = store.state.userInfo;
                    console.log(userInfo.userId,arr.ids)
                    if(arr.ids=='all' || this.inArray(userInfo.userId,arr.ids)){msgList.is_at=1;}
                }
            }
            var oldmsglist = store.state.chatlist[key];
            msgList = Object.assign(oldmsglist, msgList);//console.log(msgList);
			store.dispatch('updateChatListInfoById', {
				userId: key,
				data: msgList
			});
            this.setMsgList({
			    userId,
				conversation_id: conversation_id,
				action: 'push',
				save: true,
				data:msgOffline
			});
		});
	},
	async setMsgList({
	    userId,
		conversation_id,
		action = 'set',
		data,
        replace_id,
		save
	}) {
	   if(data){
            var objtype=Object.prototype.toString.call(data);
            if(objtype=='[object Object]' && !data.sendtype)data.sendtype='s';
	   }
	   //console.log('setMsgList',{conversation_id,action,data});
		store.dispatch('getchatDatalist',conversation_id);
		var msgList = store.state.chatDatalist[conversation_id].list
        
        //console.log(msgList);
		if (!Array.isArray(data)) {
			data = [data]
		}
		if (save) {
        //console.log(2,data);
			//if (data.length > 1) {
			//	console.error('save 不能保存数组');return;
		//	}
            var storagedata = data[0];
			let dataindex = msgList.findIndex(msg =>  (msg.id && msg.id == storagedata.id) || (msg.msgId=='local' && msg.time==storagedata.time) );
            if(dataindex==-1){
                if(!storagedata.conversation_id)storagedata.conversation_id=conversation_id;
			    data = [uniImStorage.append(storagedata)]
            }
            //console.log(data);
            if(!data[0].id)return data[0];
		}
		switch (action) {
			case 'set':
				msgList = data
				break;
			case 'push':
				msgList.push(...data)
				break;
			case 'unshift':
				msgList.unshift(...data)
				break;
			case 'update':
                var index='';
                if(!data[0].cache_id)data[0].cache_id = data[0].id;
                if(!data[0].id)data[0].id = data[0].cache_id;
                if(replace_id){//去掉
				    index = msgList.findIndex(msg =>  msg.progress_show==1 && msg.msg_id && msg.msg_id == replace_id)
                }else{
				    index = msgList.findIndex(msg =>  msg.id && msg.id == data[0].id)
                }            
				// console.log(6, msgList[index])
				// console.log(6, data[0])
				msgList[index] = Object.assign(msgList[index], data[0])
				break;
			default:
				break;
		}
        if(replace_id){//去掉
            msgList = msgList.filter((item) => {
              return item.msg_id != replace_id;
            })
        }
        store.dispatch('updateChatById', {
    		conversation_id: conversation_id,
    		data: msgList
    	});
    	store.dispatch('tabBarpull');
    	store.dispatch('updateChatDataState',userId);
    
		if (save) {
			return data[0]
		}
		return data
	},
	getConversationId(toid, type = 'single',current_uid) { //SINGLE GROUP
        if(!current_uid){
            var userInfo = store.state.userInfo;
            current_uid = userInfo.userId
        }
		if (!current_uid) {current_uid=0;
			console.error('错误current_uid不能为空', current_uid);
		}
        var param  = [toid,current_uid];
		return type+'_' + param.sort().join('_');
	},
    async pushSendingMsg(//发送中消息
		msgContent, //内容
		msgType, //消息类型
		windowType, //聊天室类型SINGLE GROUP
		userId,
        msg_id,
        sendingtype,othermsg
    ){
        if(sendingtype=='success'){//结束发送
            this.pushOutMsg({
				msgContent: msgContent,
				msgType: msgType,
				windowType: windowType,
				userId: userId,
                replace_id:msg_id
			});
        }else{
            var key  = windowType=="GROUP"?"GROUP"+userId:userId;
            var conversation_id =  this.getConversationId(userId,windowType);
		    var userInfo = store.state.userInfo;
			store.dispatch('getchatDatalist',conversation_id);
			store.dispatch('getChatList');
			var chatWindowData = store.state.chatDatalist[conversation_id].list
			var chatListInfo = store.state.chatlist[key]
            
			var time = this.getNewDate('format',true);
			//离线消息体 自己的消息
			var msgOffline = {
				userId: userInfo.userId,
				personId: userInfo.userId,
				nickName: userInfo.nickName,
				portrait: userInfo.portrait,
				msgType: msgType,
				content: msgContent,
				time: time,
				type: 2,
				msgId:'local',
				msg_id:msg_id,
                create_time : Date.now(),
				windowType: windowType
			};
            if(othermsg){for(var i in othermsg){msgOffline[i]=othermsg[i];}}
            var newData = this.pushList(chatWindowData,msgOffline);
            //console.log(chatWindowData,newData);
			store.dispatch('updateChatById', {
				conversation_id: conversation_id,
				data: newData
			});
			store.dispatch('tabBarpull');
			store.dispatch('updateChatDataState',userId);
        }
    },
    pushList(list,data,replace_id){
        var _this=this;//console.log(listlength,replace_id);
        var listlength = list.length;
        if(listlength>0){
            var is_in = false;
            for(let i = 0;i<listlength;i++){
                if(list[i].msg_id && list[i].msg_id==data.msg_id){//已存在替换
                    is_in=true;//console.log(list[i].msg_id,data.msg_id,replace_id);
                    if(data.progress_num>list[i].progress_num || replace_id){
                        list[i] = data;//console.log(data);
                        if(replace_id)list[i].msg_id = replace_id; 
                    }
                }
                if(listlength==(i+1) && !is_in){//最后一次循环
                    list.push(data);//console.log(data);
                    if(replace_id)list[i].msg_id = replace_id; 
                }
            }
        }else{//console.log(data);
            list.push(data);
        }
        return list;
    },
    pushAlertMsg({//发送alert消息
		msgContent, //内容
		windowType, //聊天室类型SINGLE GROUP
		userId,
    }){
            var conversation_id =  this.getConversationId(userId,windowType);
		    var userInfo = store.state.userInfo;
			store.dispatch('getchatDatalist',conversation_id);//console.log(userId,userInfo.userId,conversation_id);
			var chatWindowData = store.state.chatDatalist[conversation_id].list
            
			var time = this.getNewDate('format',true);
			//离线消息体 自己的消息
			var msgOffline = {
				userId: userInfo.userId,
				personId: userInfo.userId,
				nickName: userInfo.nickName,
				portrait: userInfo.portrait,
				msgType: 'ALERT',
				content: msgContent,
				time: time,
				type: 3,
				msgId:'local',
                create_time : Date.now(),
				windowType: windowType
			};
            this.setMsgList({
			    userId,
				conversation_id: conversation_id,
				action: 'push',
				save: true,
				data:msgOffline
			});
    },
	//发送消息
	pushOutMsg({
		msgContent, //内容
		msgType, //消息类型
		windowType, //聊天室类型SINGLE GROUP
		userId,
        replace_id//清除msg_id
	}) {
		var msgTypeLabel = ''; //消息类型
		if (msgType == 'TEXT' ||　msgType == 'TEXTAT' || msgType == 'ALERT') {
			msgTypeLabel = msgContent;
		}
		if (msgType == 'IMAGE') {
			msgTypeLabel = '[图片]';
		}
		if (msgType == 'VOICE') {
			msgTypeLabel = '[语音]';
		}
		if (msgType == 'VIDEO') {
			msgTypeLabel = '[视频]';
		}
		if (msgType == 'LOCATION') {
			msgTypeLabel = '[位置]';
		}
		if (msgType == 'COLLECTION') {
			msgTypeLabel = '[收藏]';
		}
		if (msgType == 'CARD') {
			msgTypeLabel = '[名片]';
		}
		if (msgType == 'FILE') {
			msgTypeLabel = '[文件]';
		}
		if (msgType == 'TRTC_VOICE_END') {
			msgTypeLabel = '[语音通话]'
		}
		if (msgType == 'TRTC_VIDEO_END') {
			msgTypeLabel = '[视频通话]'
		}
		if (msgType == 'manyMsg') {
			msgTypeLabel = '[聊天记录]';
		}
		var userInfo = store.state.userInfo;
        var key  = windowType=="GROUP"?"GROUP"+userId:userId;
		store.dispatch('createChatObj',{
			userId:userId,
			windowType:windowType,
		}).then(async res=>{
            var conversation_id =  this.getConversationId(userId,windowType);
			var localData=res.data
			store.dispatch('getchatDatalist',conversation_id);
			store.dispatch('getChatList');
			var chatWindowData = store.state.chatDatalist[conversation_id].list
			var chatListInfo = store.state.chatlist[key]
			var time = this.getNewDate('format',true)
			//在线消息体
			var msgOnlie={}
			//聊天记录
			var msgList={}
			var url=''
			if(windowType=='SINGLE'){
				msgOnlie = {
					userId: userId,
					msgType: msgType,
					content: msgContent
				}
				url='/chat/sendMsg'
				msgList = {
					userId: userId,
					personId: userInfo.userId,
					nickName: localData.fromInfo.nickName,
					portrait: localData.fromInfo.portrait,
					content: msgTypeLabel,
					time: time,
					num: chatListInfo.disturb=='Y' ? 'dot' : (chatListInfo.num ? chatListInfo.num : 0),
					windowType: windowType,
					disturb:chatListInfo.disturb ? chatListInfo.disturb : 'N',//是否静默消息
					top:chatListInfo.top ? chatListInfo.top : 'N',//是否置顶
					userType:localData.fromInfo.userType
				}
			}
			if(windowType=='GROUP'){
				msgOnlie = {
					groupId: userId,
					msgType: msgType,
					content: msgContent
				}
				url='/group/sendMsg'
				msgList = {
					userId: userId,
					personId: userInfo.userId,
				    personName:userInfo.nickName,
					nickName: localData.groupInfo.nickName,
					portrait: localData.groupInfo.portrait,
					content: msgTypeLabel,
					time: time,
					num: chatListInfo.disturb=='Y' ? 'dot' : (chatListInfo.num ? chatListInfo.num : 0),
					windowType: windowType,
					disturb:chatListInfo.disturb ? chatListInfo.disturb : 'N',//是否静默消息
					top:chatListInfo.top ? chatListInfo.top : 'N',//是否置顶
					userType:'GROUP'
				}
			}
			//离线消息体 自己的消息
			var msgOffline = {
				userId: userInfo.userId,
				personId: userInfo.userId,
				nickName: userInfo.nickName,
				portrait: userInfo.portrait,
				msgType: msgType,
				content: msgContent,
				time: time,
                create_time : Date.now(),
				type: 2,
				msgId:'local',
				windowType: windowType
			};
           	msgOffline.conversation_id = conversation_id;
			let resMsg = await this.setMsgList({
			    userId,
				conversation_id: conversation_id,
				action: 'push',
				save: true,
				data:msgOffline
			});//console.log(resMsg);
            var cache_id = resMsg.cache_id?resMsg.cache_id:resMsg.id;
            if(!cache_id){
                setTimeout(()=>{
                    this.pushOutMsg({
                		msgContent, //内容
                		msgType, //消息类型
                		windowType, //聊天室类型SINGLE GROUP
                		userId,
                        replace_id//清除msg_id
                	});
                },1000);return;
            }
           	msgOffline.cache_id = cache_id;
            msgOnlie.cache_id = cache_id;
			//离线/发送失败错误消息体
			var msgNotSend = {
				userId: userInfo.userId,
				portrait: userInfo.portrait,
				msgType: msgType,
				content: msgContent,
                cache_id: cache_id,
				type: 3
			};
			var msgSendType = 'wating';
			http.request({
				url: url,
				method: 'POST',
				data: JSON.stringify(msgOnlie),
				success: res => {//console.log(res.data);
					if (res.data.code == 200) {
						if (res.data.data.status !== '0') {
							msgSendType = 'error';
							msgOffline.sendtype = msgSendType;
							msgOffline.msgId=res.data.data.msgId
							msgNotSend.content = res.data.data.statusLabel;
							msgList.content = res.data.data.statusLabel;
						} else {
							msgSendType = 'success';
						}
					} else {
						msgSendType = 'error';
						msgOffline.sendtype = msgSendType;
						msgNotSend.content = res.data.msg;
					}
                    /*if(replace_id){
                        msgOffline.msg_id = replace_id;//console.log(replace_id,msgSendType);
                        chatWindowData = this.pushList(chatWindowData,msgOffline,msgSendType);
                    }else{
                        chatWindowData.push(msgOffline);
                    }*/
                    var app = getApp();//console.log(app.globalData.conversation_id,conversation_id);
                    if(app.globalData.conversation_id && conversation_id==app.globalData.conversation_id)msgList.num=0;
                    var oldmsglist = store.state.chatlist[key];
                    msgList = Object.assign(oldmsglist, msgList);//console.log(msgList);
					store.dispatch('updateChatListInfoById', {
						userId: key,
						data: msgList
					});
					if (msgSendType == 'error') {
                        this.setMsgList({
    			            userId,replace_id,
    						conversation_id: conversation_id,
    						action: 'update',
    						data:msgNotSend
    					});
					}else{
                        this.setMsgList({
    			            userId,replace_id,
    						conversation_id: conversation_id,
    						action: 'update',
    						data:msgOffline
    					});
					}
				},
				fail: res => {
					msgSendType = 'error';
					msgOffline.sendtype = msgSendType;
                    this.setMsgList({
			            userId,replace_id,
						conversation_id: conversation_id,
						action: 'update',
						data:msgOffline
					});
				}
			});
		});
	},
	//H5保存base64图片
	h5SaveBase64Img({
		base64
	}) {
		var arr = base64.split(',');
		var bytes = atob(arr[1]);
		let ab = new ArrayBuffer(bytes.length);
		let ia = new Uint8Array(ab);
		for (let i = 0; i < bytes.length; i++) {
			ia[i] = bytes.charCodeAt(i);
		}
		var blob = new Blob([ab], {
			type: 'application/octet-stream'
		});
		var url = URL.createObjectURL(blob);
		var a = document.createElement('a');
		a.href = url;
		a.download = new Date().getTime() + ".png";
		var e = document.createEvent('MouseEvents');
		e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		a.dispatchEvent(e);
		URL.revokeObjectURL(url);
	},
	//APP保存base64图片
	plusSaveBase64Img({
		base64
	}) {
		//url链接
		if(base64.indexOf('http') >= 0){
			uni.downloadFile({
				url: base64,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function () {
								uni.showToast({
									title: '图片保存成功',
									icon: 'none'
								})
							}
						});
					}
				}
			});
		}else if(base64.indexOf('base64') >= 0){
			const bitmap = new plus.nativeObj.Bitmap("test");
			bitmap.loadBase64Data(base64, function() {
				const url = new Date().getTime() + ".png"; // url为时间戳命名方式
				bitmap.save(url, {
					overwrite: true, // 是否覆盖
				}, (i) => {
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success: function() {
							uni.showToast({
								title: '图片保存成功',
								icon: 'none'
							})
							bitmap.clear()
						}
					});
				}, (e) => {
					uni.showToast({
						title: '图片保存失败',
						icon: 'none'
					})
					bitmap.clear()
				});
			}, (e) => {
				uni.showToast({
					title: '图片保存失败',
					icon: 'none'
				})
				bitmap.clear()
			});
		}else{
		    var self = this;
			uni.getImageInfo({
				src: base64,
				success: function(sres) {
					uni.saveImageToPhotosAlbum({
						filePath: sres.path,
						success: function(fres) {
							if (fres.errMsg == 'saveImageToPhotosAlbum:ok') {
								uni.showToast({
									title: '图片保存成功',
									icon: 'none'
								})
							} else {
							     uni.showToast({
									title: '保存失败,请重新保存',
									icon: 'none'
								})
							}
						}
					});
				}
			});
		}
	},
	// 寻找数组中的对象中的key对应值的对象
	arrFindkey({
		arr, //数组[{id:'1'}]
		key, //key键值'id'
		val //值 '1'
	}) {
		var item = arr.find(function(obj, i, arr) {
			return obj[key] === val
		})
		var index = arr.findIndex(function(obj, i, arr) {
			return obj[key] === val
		})
		return {
			item: item,
			index: index
		}
	},
	//APP下载文件
	plusDownload({
		onlinePath,
		savePath = 'file://storage/emulated/0/Documents/tengyun/'
	}) {
		return new Promise((resolve, reject) => {
			// #ifdef H5
			reject('下载失败，H5不支持plus')
			return
			// #endif
			var fname = onlinePath.split("/").pop()
			var localPath = savePath + fname
			plus.io.resolveLocalFileSystemURL( //检测本地是否存在
				localPath,
				(entry) => {
					console.log('文件已存在' + entry.name)
					resolve(entry.fullPath)
				},
				(e) => {
					console.log('文件不存在：' + e.message);
					uni.showLoading({
						title: '加载中'
					})
					createDownload(onlinePath)
				}
			);

			function createDownload(e) {
				let downloadOptions = {
					method: "GET",
					timeout: 120,
					retryInterval: 10,
					filename: savePath
				};
				// https://www.html5plus.org/doc/zh_cn/downloader.html#plus.downloader.Download
				var dtask = plus.downloader.createDownload(e, downloadOptions, function(download, status) {
					uni.hideLoading()
					// 下载完成
					if (status == 200) {
						resolve(download.filename)
					} else {
						reject({
							status: status,
							msg: '下载失败'
						})
					}
				});
				dtask.start();
			}
		})
	},
	//APP打开文件
	plusOpenFile({
		filePath
	}) {

		let system = uni.getSystemInfoSync().platform;
		if (system == 'ios') {
			filePath = encodeURI(filePath);
		}
		uni.openDocument({
			filePath,
			success: res => {
				// console.log('打开文件成功');
			},
			fail: res => {
				console.log(res);
			}
		});
	},
	// 汉字拼音A-Z排序
	sortList({
		list,
		key
	}) {
		var sortKey = [] //字母
		list.forEach(item => {
			let firstChar = ''
			item[key] = item[key] ? item[key].trim() : ""
			if (item[key]) { // 如传入空字符串，getCamelFistChar错误地返回Y
				firstChar = pinyin.getCamelFistChar(item[key]).toUpperCase() // 如字母开头，将返回字母且保留原大小写;一律改为大写
				var reg = /^\d+$/;
				if (reg.test(firstChar)) {
					firstChar = 'Z#'
				}
				item.sort = firstChar
				sortKey.push(firstChar)
			}
		})
		sortKey = [...new Set(sortKey)]
		list.sort((a, b) => a.sort.localeCompare(b.sort, 'zh')) //排序
		sortKey.sort((a, b) => a.localeCompare(b, 'zh')) //排序
		var sortlist = []
		for (var i = 0; i < sortKey.length; i++) {
			var sort = sortKey[i]
			if (sort == 'Z#') {
				sort = '#'
			}
			sortlist.push({
				letter: sort,
				data: []
			})
			for (var j = 0; j < list.length; j++) {
				var item = list[j]
				if (item.sort == 'Z#') {
					item.sort = '#'
				}
				if (item.sort == sort) {
					sortlist[i].data.push(item)
				}
			}
		}
		return sortlist
	},
	saoyisao(){//扫一扫
		// #ifdef APP-PLUS
		uni.scanCode({
			success: (res)=> {
				var result = res.result;
				if(result.indexOf('http') >= 0){
					var urlStr = result.split('?')[1];
					var invite = '';
					if(urlStr){
						var paramsArr = urlStr.split('&');
						if(paramsArr){
							for(var i = 0,len = paramsArr.length;i < len; i++){
							    // 再通过 = 将每一个参数分割为 key:value 的形式
							    var arr = paramsArr[i].split('=');
								if(arr[0] == 'invite'){
									invite = arr[1];
									break;
								}
							}
						}
					}
					if(invite){
						uni.navigateTo({
							url:this.get_package_name()+'personInfo/detail?param='+invite+'&source=1'
						})
						return;
					}
				}
				uni.navigateTo({
					url: this.get_package_name()+'favorites/textdetails?text=' + result
				});
				// var data=res.result.split(':')
				// var type=data[0]
				// var value=data[1]
				// switch (type){
				// 	case 'group':
				// 	uni.navigateTo({
				// 		url:this.get_package_name()+'groupInfo/scanCodeDetail?param='+result
				// 	})
				// 		break;
				// 	case 'user':
				// 	uni.navigateTo({
				// 		url:this.get_package_name()+'personInfo/detail?param='+value+'&source=1'
				// 	})
				// 		break;
				// 	default:
				// 		break;
				// }
			}
		});
		// #endif
		// #ifndef APP-PLUS
		uni.showToast({
			title:'扫一扫',
			icon:'none'
		})
		// #endif
	},
	// 设置原生titleNView导航文字
	setTitleNViewBtns(index,text,fontsize){
		let pages = getCurrentPages();
		let page = pages[pages.length - 1];
		// #ifdef APP-PLUS
		let currentWebview = page.$getAppWebview();
		let titleObj = currentWebview.getStyle().titleNView;
		if (!titleObj.buttons) {
			return;
		}
		titleObj.buttons[index].text = text;
		titleObj.buttons[index].fontSize = fontsize ? fontsize : titleObj.buttons[index].fontSize;
		currentWebview.setStyle({
			titleNView: titleObj
		});
		// #endif
	},
	debounce(func, wait = 1000, immediate = true){
		/**
		 * @desc 函数防抖
		 * @param func 目标函数
		 * @param wait 延迟执行毫秒数
		 * @param immediate true - 立即执行， false - 延迟执行
		 */
		let timer;
		return function() {
			let args = arguments;
			if (timer) {
				//console.log('拦截')
				clearTimeout(timer);
			}
			if (immediate) {
				let callNow = !timer;
				timer = setTimeout(() => {
					timer = null;
				}, wait);
				if (callNow){
					func.apply(this, args);
				}
			} else {
				timer = setTimeout(() => {
					func.apply(this, args);
				}, wait)
			}
		}
	},
    getType(name){
        if(!name)return 'txt';
        var arr = name.split('.');
        return arr[(arr.length-1)];
    },
	//获取文件类型图片
	getFileType(type){
		if(type == 'doc' || type == 'docx'){
			return '/static/img/file_icon/doc.png';
		}else if(type == 'wps'){
			return '/static/img/file_icon/wps.png';
		}else if(type == 'xls' || type == 'xlsx'){
			return '/static/img/file_icon/xls.png';
		}else if(type == 'pdf'){
			return '/static/img/file_icon/pdf.png';
		}else if(type == 'mp4'){
			return '/static/img/file_icon/mp4.png';
		}else if(type == 'mp3'){
			return '/static/img/file_icon/mp3.png';
		}else if(type == 'apk'){
			return '/static/img/file_icon/apk.png';
		}else if(type == 'rar'){
			return '/static/img/file_icon/rar.png';
		}else if(type == 'zip'){
			return '/static/img/file_icon/zip.png';
		}else if(type == 'txt'){
			return '/static/img/file_icon/txt.png';
		}else{
			return '/static/img/file_icon/qita.png';
		}
	},
    sizeFilter(bytesize) {
        if(!isNaN(bytesize) && typeof bytesize === 'number' ){
            let $i = 0
            // 当bytesize 大于是1024字节时，开始循环，当循环到第4次时跳出；
              while (Math.abs(bytesize) >= 1024) {
                bytesize = bytesize / 1024
                $i++
                if ($i === 4) break
              }
              // 将Bytes,KB,MB,GB,TB定义成一维数组；
              const units = ['B', 'KB', 'MB', 'GB', 'TB']
              const newsize = Math.round(bytesize, 2)
              return newsize + ' ' + units[$i];
        }else{
            return bytesize;
        }
    },
	throttle (func, wait = 1000, type = 1) {
		/**
		 * @desc 函数节流
		 * @param func 函数
		 * @param wait 延迟执行毫秒数
		 * @param type 1 使用表时间戳，在时间段开始的时候触发 2 使用表定时器，在时间段结束的时候触发
		 */
		let previous = 0;
		let timeout;
		return function() {
			let context = this;
			let args = arguments;
			if (type === 1) {
				let now = Date.now();
	
				if (now - previous > wait) {
					func.apply(context, args);
					previous = now;
				}
			} else if (type === 2) {
				if (!timeout) {
					timeout = setTimeout(() => {
						timeout = null;
						func.apply(context, args)
					}, wait)
				}
			}
		}
	},
	//文本消息链接识别
	textGetUrl({
		content
	}) {
	    if(!content)return content;
        content = this.filteremoji(content);
		var desc_Contents = [];
		var reg = /(http:\/\/|https:\/\/|www.)((\w|=|\?|\.|\/|&|-)+)/g;
		var urls = content.match(reg);
		if(urls != null){
			for(var i = 0; i < urls.length; i++){
				var index = content.indexOf(urls[i]);
				if(index > 0){
					var tet = content.substring(0,index);
					var desc = {};
					desc.type = 'text';
					desc.text = tet;
					desc_Contents.push(desc);
				}else{
					var tet = '';
				}
				var desc = {};
				desc.type = 'url';
				desc.text = urls[i];
				desc_Contents.push(desc);
				content = content.replace(tet+urls[i],'');
			}
		}
		if(content != ''){
			var desc = {};
			desc.type = 'text';
			desc.text = content;
			desc_Contents.push(desc);
		}
		return desc_Contents;
	},
    ToastBack(title,delta,time,icon){
        if(title){
            if(!icon)icon='none';
            uni.showToast({
				title: title,
				icon: icon
			})
        }
        if(!delta)delta=1;
        if(!time)time=1000;
        setTimeout(()=>{
            uni.navigateBack({
    			delta: delta
    		})
        },time);
    },
    //判断是否支持emoji表情
    check_emoji(){
        var SystemInfo = uni.getSystemInfoSync();
        var osVersion = parseFloat(SystemInfo.osVersion);
        if(SystemInfo.platform=='android' && osVersion<6)return false;
        return true;
    },//格式化表情
    filteremoji(substring){
        if(this.is_empty(substring))return '';
        var def = '[表情]';
        if(substring==def)return def;
        if(!this.check_emoji()){
        for ( var i = 0; i < substring.length; i++) {
            var hs = substring.charCodeAt(i);  
            if (0xd800 <= hs && hs <= 0xdbff) {  
                if (substring.length > 1) {  
                    var ls = substring.charCodeAt(i + 1);  
                    var uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;  
                    if (0x1d000 <= uc && uc <= 0x1f77f) {return def;}  
                }  
            } else if (substring.length > 1) {  
                var ls = substring.charCodeAt(i + 1);  
                if (ls == 0x20e3) {return def;}  
            } else {  
                if (0x2100 <= hs && hs <= 0x27ff) {  
                    return def;  
                } else if (0x2B05 <= hs && hs <= 0x2b07) {  
                    return def;  
                } else if (0x2934 <= hs && hs <= 0x2935) {  
                    return def;  
                } else if (0x3297 <= hs && hs <= 0x3299) {  
                    return def;  
                } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030  
                        || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b  
                        || hs == 0x2b50) {  
                    return def;  
                }  
            }  
        }}
        return substring;
    },//判断是否是空值
    is_empty(obj){
        if (!obj || obj=='') return true; 
        if (typeof obj === "string") {
          obj = obj.replace(/\s*/g, "");//移除字符串中所有 ''
          if (obj === '') return true;
        } 
        return (Array.isArray(obj) && obj.length === 0) || (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0);
    },
    get_package_name(type){
        var app = getApp();
        if(type==1)return app.globalData.package_name;
        return '/'+app.globalData.package_name+'/';
    },
	//打开url
	goWebUrl({
		url
	}) {
		if(url.substr(0,2)=='//')url='http:'+url;
		if(url.substr(0,4)!='http')url='http://'+url;
		// #ifdef H5
			location.href = url;
		// #endif
		// #ifndef H5
			uni.navigateTo({
				url: this.get_package_name()+'webview/webview?weburl=' + url
			});
		// #endif
	},
    url_query(str,field){
        var arr1=str.split('?')
        var arr2=arr1[1].split('#')
        var arr3=arr2[0].split('&')
        var obj={};
        for(var i=0;i<arr3.length;i++){
            var arr4=arr3[i].split('=')
            if(obj[arr4[0]] !== undefined){//[] ,1,0
                if(!(obj[arr4[0]] instanceof Array)){
                    obj[arr4[0]]= [obj[arr4[0]]]
                }
            obj[arr4[0]].push(arr4[1])
            }else{
                if(arr4[1]){
                    obj[arr4[0]]= arr4[1]
                }
            }
        }
        if(field){
            return this.is_empty(obj[field])?'':obj[field];
        }
        return obj;
    },
	//APP权限验证
	async appCheckAuth(auth_name,android_name,ios_name){
		var status = 1;
		// #ifdef APP-PLUS
			if(plus.os.name == "iOS"){
				var is_check = await appcheckauth.judgeIosPermission(ios_name);
				if(is_check){
					status = 1;
				}else{
					status = 0;
				}
			}else{
				var is_check = await appcheckauth.requestAndroidPermission(android_name);
				if(is_check == 1){
					status = 1;
				}else{
					status = 0;
				}
			}
			if(status == 0){
				uni.showModal({
				    content: '当前功能需要' + auth_name + '权限，请前往应用权限设置中开启',
				    confirmText: "去开启",
				    success: function(res) {
				        if (res.confirm) {
				            appcheckauth.gotoAppPermissionSetting();
				        }
				    }
				})
			}
		// #endif
		return status;
	},
	setGroupApply(groupId,isadd,count){
		store.dispatch('createChatObj', {
			userId: groupId,
			windowType: 'GROUP'
		})
		.then(res => {
			store.dispatch('getchatDatalist');
			store.dispatch('getChatList');
			var key  = "GROUP"+groupId;
			var data = store.state.chatlist && store.state.chatlist[key] ? store.state.chatlist[key] : {};
			var addGroupApply = data.addGroupApply ? data.addGroupApply : 0;
			if(isadd == 1){
				addGroupApply = addGroupApply * 1 + count * 1;
			}else{
				addGroupApply = addGroupApply * 1 - count * 1;
			}
			addGroupApply = addGroupApply > 0 ? addGroupApply : 0;
			data.addGroupApply = addGroupApply;
			store.dispatch('updateChatListInfoById', {
				userId: key,
				data: data
			});
			store.dispatch('getchatDatalist');
			store.dispatch('getChatList');
		});
	},
}
